<template>
  <el-form
    :model="ruleForm"
    status-icon
    :rules="rules"
    ref="ruleForm"
    label-width="100px"
    class="demo-ruleForm"
  >
    <el-form-item
      label="原密码"
      prop="oldPass"
    >
      <el-input
        type="password"
        v-model="ruleForm.oldPass"
        placeholder="请输入原密码"
      ></el-input>
    </el-form-item>
    <el-form-item
      label="新密码"
      prop="newPass"
    >
      <el-input
        type="password"
        v-model="ruleForm.newPass"
        autocomplete="off"
        placeholder="请设置新密码"
      ></el-input>
    </el-form-item>
    <el-form-item
      label="重复新密码"
      prop="checkNewPass"
    >
      <el-input
        type="password"
        v-model="ruleForm.checkNewPass"
        autocomplete="off"
        placeholder="请确认新密码"
      ></el-input>
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        @click="submitForm('ruleForm')"
      >更改</el-button>
      <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  name: 'SetPassword',
  data () {
    var validateNewPass = (rule, value, callback) => {
      if (value === this.ruleForm.oldPass) {
        callback(new Error('新密码不能与原密码相同!')
        )
      } else {
        if (this.ruleForm.checkNewPass !== '') {
          this.$refs.ruleForm.validateField('checkNewPass')
        }
        callback()
      }
    }
    var validateNewPass2 = (rule, value, callback) => {
      if (value !== this.ruleForm.newPass) {
        callback(new Error('与新密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      ruleForm: {
        oldPass: '',
        newPass: '',
        checkNewPass: ''
      },
      rules: {
        oldPass: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        newPass: [
          { required: true, message: '请设置新密码', trigger: 'blur' },
          { validator: validateNewPass, trigger: 'blur' }
        ],
        checkNewPass: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          { validator: validateNewPass2, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
</style>
